package com.tanhua.manage.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manage.mapper.AnalysisByDayMapper;
import com.tanhua.manage.mapper.UserMapper;
import com.tanhua.manage.pojo.AnalysisByDay;
import com.tanhua.manage.vo.DashboardVo;
import com.tanhua.manage.vo.SummaryVo;
import com.tanhua.manage.vo.UsersVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * yan
 */
@Service
public class HomeYanService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    private UserMapper userMapper;

    //101 新增 102 活跃用户 103 次日留存率
    private static final long Registered = 101;
    private static final long Active = 102;
    private static final long Retention1d = 103;


    /**
     * 查询概要统计信息
     *
     * @return
     */
    public SummaryVo querySummary() {


        //查询累计用户  tb_user
        Integer cumulativeUsers = this.userMapper.selectCount(new QueryWrapper<>());

        //查询过去30天活跃用户
        Long time1 = System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000;
        Integer activePassMonth = getActiveNum(time1);

        //过去7天活跃用户
        Long time2 = System.currentTimeMillis() - 7L * 24 * 60 * 60 * 1000;
        Integer activePassWeek = getActiveNum(time2);


        //今日AnalysisByDay数据信息
        AnalysisByDay todayAnalysisByDay = this.getAnalysisByDay(new Date(System.currentTimeMillis()));

        Integer newUsersToday = 0;
        Integer loginTimesToday = 0;
        Integer activeUsersToday = 0;

        if (null != todayAnalysisByDay) {
            // 今日新增用户
            newUsersToday = todayAnalysisByDay.getNumRegistered();
            // 今日登录次数
            loginTimesToday = todayAnalysisByDay.getNumLogin();
            // 今日活跃用户
            activeUsersToday = todayAnalysisByDay.getNumActive();
        }


        //昨日AnalysisByDay数据信息
        AnalysisByDay yesterdayAnalysisByDay = this.getAnalysisByDay(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));


        Integer newUsersYesterday = 0;
        Integer loginTimesYesterday = 0;
        Integer activeUsersYesterday = 0;


        if (null != yesterdayAnalysisByDay) {
            // 昨日新增用户
            newUsersYesterday = yesterdayAnalysisByDay.getNumRegistered();
            // 昨日登录次数
            loginTimesYesterday = yesterdayAnalysisByDay.getNumLogin();
            // 昨日活跃用户
            activeUsersYesterday = yesterdayAnalysisByDay.getNumActive();
        }

        Integer activeUsersqianday = 0;
        // 前日活跃用户
        AnalysisByDay analysisByQianDay = this.getAnalysisByDay(new Date(System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000));
        if (null != analysisByQianDay) {
            activeUsersqianday = analysisByQianDay.getNumActive();
        }


        // 今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        double newUsersTodayRate = 1.00 * (newUsersToday - newUsersYesterday) / newUsersYesterday;

        // 今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        double loginTimesTodayRate = 1.00 * (loginTimesToday - loginTimesYesterday) / loginTimesYesterday;

        // 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        double activeUsersTodayRate = 1.00 * (activeUsersToday - activeUsersYesterday) / activeUsersYesterday;

        // 昨日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        double activeUsersYesterdayRate = 1.00 * (activeUsersYesterday - activeUsersqianday) / activeUsersqianday;

        // 过去7天平均日使用时长，单位秒    * 随机数生成
        Integer useTimePassWeek = RandomUtils.nextInt();
        System.out.println("userTimePassWeek = " + useTimePassWeek);

        //填充数据
        SummaryVo summaryVo = new SummaryVo();
        summaryVo.setCumulativeUsers(cumulativeUsers);
        summaryVo.setActivePassMonth(activePassMonth);
        summaryVo.setActivePassWeek(activePassWeek);
        summaryVo.setNewUsersToday(newUsersToday);
        summaryVo.setNewUsersTodayRate((int) Math.floor(100 * newUsersTodayRate));
        summaryVo.setLoginTimesToday(loginTimesToday);
        summaryVo.setLoginTimesTodayRate((int) Math.floor(100 * loginTimesTodayRate));
        summaryVo.setActiveUsersToday(activeUsersToday);
        summaryVo.setActiveUsersTodayRate((int) Math.floor(100 * activeUsersTodayRate));
        summaryVo.setUseTimePassWeek(useTimePassWeek);
        summaryVo.setActiveUsersYesterday(activeUsersYesterday);
        summaryVo.setActiveUsersYesterdayRate((int) Math.floor(100 * activeUsersYesterdayRate));

        return summaryVo;
    }


    /**
     * 查询各种用户数据
     * 新增用户
     * 活跃用户
     * 次日留存用户
     * 101 新增 102 活跃用户 103 次日留存率
     *
     * @return
     */
    public UsersVo queryUsers(Long sd, Long ed, Long type) {

        Date startDate = new Date(sd);
        Date endDate = new Date(ed);

        Date lastStartDate = new Date(startDate.getYear()-1,startDate.getMonth(),startDate.getDate());
        Date lastEndDate = new Date(endDate.getYear()-1,endDate.getMonth(),endDate.getDate());

        //去年
        ArrayList<DashboardVo> lastYearList = getTimeRangeInfo(type, lastStartDate, lastEndDate);
        //今年
        ArrayList<DashboardVo> thisYearList = getTimeRangeInfo(type, startDate, endDate);

        return new UsersVo(thisYearList,lastYearList);
    }

    //时间区间内信息
    private ArrayList<DashboardVo> getTimeRangeInfo(Long type, Date start, Date end) {

        ArrayList<DashboardVo> List = new ArrayList<>();

        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("record_date", start).lt("record_date", end);
        List<AnalysisByDay> AnalysisByDayList = this.analysisByDayMapper.selectList(queryWrapper);

        if (null != AnalysisByDayList) {
            for (AnalysisByDay analysisByDay : AnalysisByDayList) {
                DashboardVo dashboardVo = new DashboardVo();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dashboardVo.setTitle(simpleDateFormat.format(analysisByDay.getRecordDate()));
                if (type == Registered) {
                    dashboardVo.setAmount(analysisByDay.getNumRegistered());
                } else if (type == Active) {
                    dashboardVo.setAmount(analysisByDay.getNumActive());
                } else if (type == Retention1d) {
                    dashboardVo.setAmount(analysisByDay.getNumRetention1d());
                }


                List.add(dashboardVo);
            }
        }
        return List;
    }


    /**
     * 根据指定日期查询数据库
     *
     * @param date
     * @return
     */
    public AnalysisByDay getAnalysisByDay(Date date) {
        QueryWrapper<AnalysisByDay> query = new QueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date appointDate = null;
        try {
            appointDate = simpleDateFormat.parse(simpleDateFormat.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        query.eq("record_date", appointDate);
        AnalysisByDay analysisByDay = this.analysisByDayMapper.selectOne(query);
        return analysisByDay;
    }

    private Integer getActiveNum(Long time) {
        QueryWrapper<AnalysisByDay> query = new QueryWrapper<>();
        query.gt("record_date", new Date(time));
        List<AnalysisByDay> analysisByDays = this.analysisByDayMapper.selectList(query);
        Integer activeNum = 0;
        for (AnalysisByDay analysisByDay : analysisByDays) {
            activeNum += analysisByDay.getNumActive();
        }
        return activeNum;
    }


}
